package org.Niu.client;

import lombok.AllArgsConstructor;
import org.Niu.client.nettyImpl.NettyRpcClient;
import org.Niu.common.message.RpcRequest;
import org.Niu.common.message.RpcResponse;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;

@AllArgsConstructor
public class ClientProxy implements InvocationHandler {
//    String host;
//    int port;

    private RpcClient rpcClient;
    public ClientProxy(){
        rpcClient=new NettyRpcClient();
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        RpcRequest request = RpcRequest.builder()
                .interfaceName(method.getDeclaringClass().getName())
                .params(args)
                .paramsType(method.getParameterTypes())
                .methodName(method.getName())
                .build();
        // getParameters() 获取的是参数信息，参数名称，类型啥的，并没有实际参数值
        // System.out.println("getParameters ------ " + method.getParameters());
        // RpcResponse rpcResponse = IOClient.sendRequest(host, port, request);
        NettyRpcClient nettyRpcClient = new NettyRpcClient();
        RpcResponse rpcResponse = nettyRpcClient.sendRequest(request);
        return rpcResponse.getData();
    }

    // <T> 是声明泛型
    public <T>T getProxy(Class<T> clazz){
        Object o = Proxy.newProxyInstance(clazz.getClassLoader(),new Class[]{clazz}, this);
        return (T)o;
    }

}
